//
//  LoopScrollView.m
//  HelloInstallment
//
//  Created by 文彬 on 15/1/12.
//  Copyright (c) 2015年 文彬. All rights reserved.
//

#import "WBLoopScrollView.h"

@interface WBLoopScrollView ()<UIScrollViewDelegate>

@property (nonatomic, strong) UIScrollView *scrollView;
@property (nonatomic, assign) NSInteger totalPageCount; //总页数

@property (nonatomic , strong) NSTimer *animationTimer;
@property (nonatomic , assign) NSTimeInterval animationDuration; //自动翻页间隔时间

@end

@implementation WBLoopScrollView

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

- (void)dealloc
{
    [self.animationTimer invalidate];
    self.animationTimer = nil;
}

/**
*  初始化
*
*  @param frame             frame
*  @param animationDuration 自动翻页间隔 设为0时不自动翻页
*
*  @return id
*/
- (id)initWithFrame:(CGRect)frame animationDuration:(NSTimeInterval)animationDuration
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
        
//        self.translatesAutoresizingMaskIntoConstraints = NO;
        self.animationDuration = animationDuration;
        
        self.autoresizesSubviews = YES;
        self.scrollView = [[UIScrollView alloc] initWithFrame:self.bounds];
        self.scrollView.autoresizingMask = 0xFF;
        self.scrollView.contentMode = UIViewContentModeCenter;
        self.scrollView.delegate = self;
        self.scrollView.pagingEnabled = YES;
        self.scrollView.showsHorizontalScrollIndicator = NO;
        self.scrollView.showsVerticalScrollIndicator = NO;
        [self addSubview:self.scrollView];
        
        self.pageControl = [[UIPageControl alloc]initWithFrame:CGRectMake(kUIScreenWidth-100, 15, 100, 20)];
        self.pageControl.currentPageIndicatorTintColor = RGBColor(244, 177, 45);
        self.pageControl.pageIndicatorTintColor = [UIColor whiteColor];
        [self addSubview:self.pageControl];
        self.pageControl.hidden = YES;
        
        self.pageLabel = [[UILabel alloc]init];
        self.pageLabel.font = [UIFont systemFontOfSize:14];
        self.pageLabel.textColor = [UIColor whiteColor];
        self.pageLabel.backgroundColor = [UIColor blackColor];
        self.pageLabel.frame = CGRectMake(self.frame.size.width-50, self.frame.size.height-30, 40, 20);
        self.pageLabel.textAlignment = NSTextAlignmentCenter;
        [self addSubview:self.pageLabel];
    }
    return self;
}

/**
 *  开始自动翻页
 */
- (void)startTimer
{
    if (!self.animationTimer&&self.animationDuration>0)
    {
        self.animationTimer = [NSTimer scheduledTimerWithTimeInterval:self.animationDuration target:self selector:@selector(changeLoopImage) userInfo:nil repeats:YES];
        //必须使用NSRunLoopCommonModes  否则页面操作将阻塞计时器线程
        [[NSRunLoop currentRunLoop] addTimer:self.animationTimer forMode:NSRunLoopCommonModes];
    }
}

/**
 *  停止自动翻页
 */
- (void)stopTimer
{
    if (self.animationTimer)
    {
        [self.animationTimer invalidate];
        self.animationTimer = nil;
    }
}

#pragma mark -私有函数
- (void)setDelegate:(id<WBLoopScrollViewDelegate>)delegate
{
    _delegate = delegate;
}

/**
 *  页面布局
 */
- (void)layoutPages
{
    for (UIView *view in self.scrollView.subviews)
    {
        [view removeFromSuperview];
    }
    
    
    self.totalPageCount = [self.delegate numOfTotalPageCount];
    if (self.totalPageCount>=2)
    {
        self.pageControl.hidden = NO;
        self.pageControl.numberOfPages  = self.totalPageCount;
    }
    
    self.pageLabel.text = [NSString stringWithFormat:@"1/%ld",self.totalPageCount];
    
   
    UIView *view = [self.delegate viewForPageIndex:self.totalPageCount==1?0:self.totalPageCount-1];
    view.frame = CGRectMake(0, 0, self.frame.size.width, self.frame.size.height);
    [self.scrollView addSubview:view];
    
    //只有一页时  不再需要处理
    if (self.totalPageCount==1)
    {
        self.scrollView.contentSize = CGSizeMake(self.frame.size.width, self.frame.size.height);
        return;
    }
    
    for (int i=0; i<self.totalPageCount; i++)
    {
        UIView *view = [self.delegate viewForPageIndex:i];
        view.frame = CGRectMake(self.frame.size.width*(i+1), 0, self.frame.size.width, self.frame.size.height);
        [self.scrollView addSubview:view];
    }
    
    UIView *viewLast = [self.delegate viewForPageIndex:0];
    viewLast.frame = CGRectMake(self.frame.size.width*(self.totalPageCount+1), 0, self.frame.size.width, self.frame.size.height);
    [self.scrollView addSubview:viewLast];
    
    self.scrollView.contentSize = CGSizeMake(self.frame.size.width*(self.totalPageCount+2), self.frame.size.height);
    self.scrollView.contentOffset = CGPointMake(self.frame.size.width, 0);
    
}

/**
 *  自动翻页
 */
- (void)changeLoopImage
{
    CGPoint pt = self.scrollView.contentOffset;
    int count = self.totalPageCount;
    if(pt.x == self.frame.size.width * count)
    {
        [self.scrollView setContentOffset:CGPointMake(0, 0)];
        [self.scrollView scrollRectToVisible:CGRectMake(self.frame.size.width, 0, self.scrollView.frame.size.width, self.scrollView.frame.size.height) animated:YES];
        
        [UIView animateWithDuration:0.5 animations:^(void){
            [self.scrollView scrollRectToVisible:CGRectMake(self.frame.size.width,0,self.scrollView.frame.size.width,self.scrollView.frame.size.height) animated:NO]; }];
    }
    else
    {
        [UIView animateWithDuration:0.5 animations:^(void){
            [self.scrollView scrollRectToVisible:CGRectMake(pt.x+self.frame.size.width,0,self.scrollView.frame.size.width,self.scrollView.frame.size.height) animated:NO];  }];
    }
    
}
#pragma mark--UIScrollViewDelegate
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    //手动滑动翻页时停止计时器
    [self stopTimer];
}
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    [self startTimer];
}

-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    int currentPage = floor((self.scrollView.contentOffset.x - self.scrollView.frame.size.width / (self.totalPageCount+2)) / self.scrollView.frame.size.width) + 1;
    if (currentPage==0)
    {
        //滑动到第一页的时候，再调用那个函数将ScrollView滑动到倒数第2页
        [self.scrollView scrollRectToVisible:CGRectMake(self.frame.size.width * self.totalPageCount,0,self.scrollView.frame.size.width,self.scrollView.frame.size.height) animated:NO];
    }
    else if (currentPage == (self.totalPageCount+1))
    {
        //滑动到最后一页的时候，通过调用函数scrollRectToVisible: animated:NO 将ScrollView滑动到第2页
        [self.scrollView scrollRectToVisible:CGRectMake(self.frame.size.width,0,self.scrollView.frame.size.width,self.scrollView.frame.size.height) animated:NO];
    }
    
    if ([self.delegate respondsToSelector:@selector(didScrollPage:)]) {
        [self.delegate didScrollPage:self.pageControl.currentPage];
    }
    
     self.pageLabel.text = [NSString stringWithFormat:@"%ld/%ld",self.pageControl.currentPage+1,self.totalPageCount];
}

-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    int width = scrollView.frame.size.width;
    int page = floor((scrollView.contentOffset.x - width/2)/width) + 1;
    self.pageControl.currentPage = page - 1;
    
}


@end
